package com.advertise.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.hibernate.hql.ast.tree.Case2Node;



import com.advertise.dao.UserDAO_IFace;
import com.advertise.model.LoginState;
import com.advertise.model.Menu;
import com.advertise.model.Role;
import com.advertise.model.TreeNode;
import com.advertise.model.User;
import com.advertise.model.UserState;


public class UserService_Impl extends BaseService_Impl<User, Integer> implements
		UserService_IFace {
	
	private UserDAO_IFace userDAO;

	
	public UserDAO_IFace getUserDAO() {
		return userDAO;
	}


	public void setUserDAO(UserDAO_IFace userDAO) {
		this.userDAO = userDAO;
	}

	
	public List<TreeNode> getUserMenus(String loginId){
		Set<TreeNode> userMenus=new HashSet<TreeNode>();
		User user= userDAO.getUserByLoginId(loginId);
		
		Set<Role> userRoles=user.getRoles();
		
		Iterator<Role> roleIt=userRoles.iterator();
		// Loop the user's role list and get the role's menu list
		while(roleIt.hasNext()){
			Role role=roleIt.next();
			
			Set<Menu> roleMenu=role.getRoleMenus();
			
			Iterator<Menu> menuIt=roleMenu.iterator();
			
			// Loop the every role menu and put them into a new menu list and remove the repeat item
			// because using the set collection
			// but only get the 
			while(menuIt.hasNext()){
				Menu menu=menuIt.next();
					userMenus.add(menu);
				
				
			}
		}
		
		List<TreeNode> userMenuList=new ArrayList<TreeNode>();
		
		userMenuList.addAll(userMenus);
		
		return userMenuList;
	}


	
	public LoginState validateLogin(String loginName, String password) {
		User loginUser=userDAO.getUserByLoginId(loginName);
		if(loginUser!=null && loginUser.getPassword().equals(password)){
			
			switch (loginUser.getState()) {			
			case INACTIVE :
				return LoginState.INACTIVEUSER;
			case FROZEN :
				return LoginState.FROZENUSER;
				
			case ACTIVE:
				return LoginState.LOGINSUCCESS;
				
			case DELETE:
				return LoginState.DELTEUSER;
			}
		}
		if(loginUser == null){
			return LoginState.NOUSER;
		}
		
		if(loginUser != null && !loginUser.getPassword().equals(password)){
			return LoginState.INCORRECTPASSWORD;
		}
		
		return null;
		
	}
}
